<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	/**
	 * @author Garry Willits
	 * @copyright 
	 * @date 10th May 2011
	 */
class Login  extends CI_Controller{
	//TODO - Insert your code here
	public $redirectTo;

	public function __construct( $redirect )
	{   
		parent::__construct();
		session_start();
		$this->redirectTo = $redirect;
		$this->load->database();
		$this->load->helper('url');
		$this->load->library('form_validation');
		$this->load->library('encrypt');
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$this->display = new LoginDisplay();
		$this->display->id="login";
		$this->display->scripts = 'jquery.js';
		$this->display->scripts = 'jquery-ui.js';
		$this->display->scripts = 'uiinit.js';
		$this->display->styles = 'ui';
		$this->display->styles = 'themes/smoothness/jquery.ui.all';
		$this->display->scripts = 'uiinit.js';
		$this->display->class ="grid_12 center";
		$this->display->styles = "login";
		$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
		$this->display->errors = null;
		$this->Login();
		$this->display->finalize();

	}

	protected function Login(){

		if ($this->form_validation->run() == FALSE)
		{
			$this->display->errors = $this->form_validation->_error_fields;
		}
		else
		{
			$query = $this->db->get_where('user', array('username'=>'garry','password'=>$this->hash_password($this->input->post('password'),'hashme' ) ) );
			if ($query->num_rows() > 0)
			{
					$newdata = array(
                   'username'  => $query->row()->username,
                   'email'     => $query->row()->email,
                   'logged_in' => TRUE
               );
               ini_set('session.gc_maxlifetime',20);
				ini_set('session.gc_probability',1);
				ini_set('session.gc_divisor',1); 
				$_SESSION = array_merge($_SESSION,$newdata);
				redirect($this->redirectTo);
			}
			else {
				$this->display->loginerr = TRUE;
			} 
		}
	}
	
	function hash_password($password, $nonce) {
	  return hash_hmac('sha512', $password . $nonce, $this->config->item('encryption_key'));
	}
	
}


?>